import type { DatePickerProps, InputProps } from 'element-plus'
import { reactive, toRef, toRefs } from 'vue'

import { loginLogApi } from '@/apis'
import {
  type GridExtOptions,
  TABLE_FORMAT,
  TABLE_ITEM_RENDER,
  TABLE_RENDERER,
  useGridExt
} from '@/hooks'
import { downloadFile, getElementFnFromInstance, optionsToObj } from '@/utils'

const loginStatusOptions = [
  { label: '成功', value: '0' },
  { label: '失败', value: '1' }
]

export const loginStatusObj = optionsToObj(loginStatusOptions)

export function useGrid() {
  const state = reactive({
    gridConfig: {
      showOverflow: true,
      border: true,
      loading: false,
      autoResize: true,
      height: 'auto',
      align: 'center',
      resizeConfig: {
        refreshDelay: 10
      },
      toolbarConfig: {
        custom: true,
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'loginIp',
            title: '登录地址',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'userName',
            title: '用户名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.Select,
              props: {
                placeholder: '请选择'
              } as SelectProps,
              options: loginStatusOptions
            }
          },
          {
            field: 'loginDate',
            title: '登录时间',
            itemRender: {
              name: TABLE_ITEM_RENDER.DatePicker,
              props: {
                type: 'daterange',
                startPlaceholder: '开始时间',
                endPlaceholder: '结束时间',
                valueFormat: 'YYYY-MM-DD'
              } as DatePickerProps
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columns: [
        { type: 'checkbox', width: 50 },
        {
          field: 'id',
          title: 'ID',
          width: 100
        },
        {
          field: 'userName',
          title: '用户名称'
        },
        {
          field: 'loginIp',
          title: '登录地址'
        },
        {
          field: 'loginLocation',
          title: '登录地点'
        },
        {
          field: 'browser',
          title: '浏览器'
        },
        {
          field: 'os',
          title: '操作系统'
        },
        {
          title: '登录状态',
          width: 100,
          slots: {
            default: 'columns_status'
          }
        },
        {
          field: 'msg',
          title: '操作信息'
        },
        {
          field: 'loginDate',
          title: '登录日期',
          minWidth: 100,
          formatter: TABLE_FORMAT.Date
        }
      ],
      pagerConfig: {
        background: true,
        layouts: [
          'PrevJump',
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ],
        pageSize: 15
      },
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ page, form }) => {
            form = processingForm(form)

            const data = await loginLogApi.getLoginLogPage({
              pageSize: page.pageSize,
              pageNum: page.currentPage,
              ...form
            })
            return data
          }
        }
      },
      onCheckboxChange({ checked, row }) {
        checked
          ? state.selectedIds.add(row.id)
          : state.selectedIds.delete(row.id)
      }
    } as GridExtOptions,
    selectedIds: new Set<string>()
  })

  const { gridRef, ...gridRestHook } = useGridExt(toRef(state, 'gridConfig'))
  const { $msgbox } = getElementFnFromInstance()

  /**
   * 处理请求数据
   */
  function processingForm(form: Record<string, any>) {
    return gridRestHook.processFormDateRanges(form, {
      loginDate: ['beginDate', 'endDate']
    })
  }

  /**
   * 删除
   */
  function handleDel() {
    $msgbox
      .confirm('确认删除？', '提示', { type: 'warning' })
      .then(async () => {
        await loginLogApi.deleteLoginLog({
          ids: Array.from(state.selectedIds)
        })

        gridRestHook.refresh()
      })
      .catch(() => {})
  }

  /**
   * 清空
   */
  function handleClear() {
    $msgbox
      .confirm('确认清空？', '提示', { type: 'warning' })
      .then(async () => {
        await loginLogApi.clearLoginLog()

        gridRestHook.refresh()
      })
      .catch(() => {})
  }

  /**
   * 导出
   */
  async function handleExport() {
    const { form, pager } = gridRef.value.getProxyInfo()!
    const processedForm = processingForm(form)

    try {
      gridRestHook.showLoading()

      const res = await loginLogApi.exportLoginLogPage({
        pageSize: pager.pageSize,
        pageNum: pager.currentPage,
        ...processedForm
      })

      downloadFile(res)
    } finally {
      gridRestHook.hideLoading()
    }
  }

  return {
    ...toRefs(state),
    gridRef,
    handleDel,
    handleClear,
    handleExport
  }
}
